<template>
  <div class="chat-container">
    <PrivateDetail v-if="type === 'private'" @goUserInfo="handleUserInfo" ref="privateDetailRef" />
    <GroupDetail v-else @goUserInfo="handleUserInfo" ref="groupDetailRef" />
    <div class="chat-input">
      <input type="text" v-model="message" placeholder="发送消息..." />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { chatApi } from '@/api/chat'
import { useRoute, useRouter } from 'vue-router'
import { chatService } from '@/utils/webSocket'
import PrivateDetail from './components/PrivateDetail.vue'
import GroupDetail from './components/GroupDetail.vue'

const route = useRoute()
const router = useRouter()
const { type } = route.query
const { id } = route.params
const message = ref('')
const loading = ref(false)

const privateDetailRef = ref(null)
const groupDetailRef = ref(null)

// 发送消息
const sendMessage = async () => {
  if (!message.value.trim()) return
  if (loading.value) return

  loading.value = true
  try {
    const messageData = {
      content: message.value,
      recipientId: id,
    }
    if (type === 'private') {
      await chatApi.sendMessage(messageData)
      await privateDetailRef.value.getPrivateChatList()
    } else {
      chatService.sendMessage({
        roomId: id,
        content: message.value,
        type: 'roomMessage',
      })
      await groupDetailRef.value.getGroupChatList()
    }
    message.value = ''
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleUserInfo = (id) => {
  router.push(`/user/${id}`)
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.chat-input {
  padding: 12px 16px;
  background-color: var(--bg-color);
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
  align-items: center;
}

.chat-input input {
  flex: 1;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 18px;
  padding: 0 16px;
  font-size: 14px;
  background-color: #f8f8f8;
}

.chat-input button {
  padding: 8px 20px;
  background-color: #0086f6;
  color: #fff;
  border: none;
  border-radius: 18px;
  font-size: 14px;
}
</style>
